import {
    showToast
} from "../../utils/asyncWx.js";
import {
    request
} from "../../request/index.js";
var redis = require("../../utils/redis.js").default;
Page({
    data: {
        address: {},
        cart: [],
        totalPrice: 0,
        totalNum: 0
    },
    onShow() {
        // 获取默认收货人
        this.getDefaultAddress();

        // 获取缓存中的收货地址信息
        const address = wx.getStorageSync("address");
        // 获取缓存中的购物车数据
        let cart = wx.getStorageSync("cart") || [];
        // 过滤后的购物车数组
        cart = cart.filter(v => v.checked);
        this.setData({
            address
        });
        // 总价格 总数量
        let totalPrice = 0;
        let totalNum = 0;
        cart.forEach(v => {
            totalPrice += v.num * v.goodsPrice;
            totalNum += v.num;
        })
        this.setData({
            cart,
            totalPrice,
            totalNum,
            address
        });
    },
    async getDefaultAddress() {
        // const userId = wx.getStorageSync("userId");
        const userId = redis.get("userId");
        const addressId = wx.getStorageSync('addressId');
        let url = "";
        let id = 0;
        // 存在地址id，则通过地址id查找，否则，查找默认
        if (addressId) {
            url = "/consignees/getOne";
            id = addressId;
        } else {
            url = "/consignees/getDefaultConsignee",
                id = userId;
        }
        const res = await request({
            url: url,
            data: {
                id
            }
        })
        this.setData({
            address: res.data.data
        })
    },
    selectAddress() {
        wx.navigateTo({
            url: '/pages/pay/address/index',
        })
    },
    // 点击收货地址
    handleChooseAddress() {
        wx.navigateTo({
            url: '/pages/pay/address/index',
        })
    },
    async handleOrderPay() {
        try {
            // 判断收货地址
            const {
                address
            } = this.data;
            if (!address.consigneeName) {
                await showToast({
                    title: '您还没有选择收货地址！'
                });
                return;
            }
            // 获取缓存中的token
            const token = redis.get('token');
            if (!token) {
                wx.navigateTo({
                    url: '/pages/login/index',
                });
                return;
            }
            // 创建订单
            const header = {
                token
            };
            // 请求体参数
            const goodsPrice = this.data.totalPrice;
            const consignee = this.data.address;
            const cart = this.data.cart;

            let goods = [];
            let type = 0;
            cart.forEach(v => goods.push({
                goodsId: v.id,
                number: v.num,
                goodsName: v.goodsName,
                goodsPrice: v.goodsPrice,
                goodsCoverUrl: v.coverUrl
            }))
            const orderModel = {
                goodsPrice,
                consignee,
                goods,
                type
            };
            // 4 准备发送请求 创建订单 获取订单编号
            const res = await request({
                url: "/orders/createOrder",
                method: "POST",
                data: orderModel,
                header: header
            });
            if(res.data.code === 200) {
                wx.setStorageSync('cart', []);
                wx.showToast({
                  title: '支付成功',
                })
                setTimeout(function() {
                    wx.switchTab({
                        url: '/pages/cart/index',
                      })
                }, 1000)
                
            } else {
                wx.showToast({
                  title: '请稍后再试！',
                })
            }
        } catch (error) {
            await showToast({
                title: "支付失败"
            })
            console.log(error);
        }
    }
})